package com.example.cotrller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.example.Pay.alipay.Alipay;
import com.example.pojo.PayLog;
import com.example.pojo.Refundlog;
import com.example.pojo.Statistics;
import com.example.service.PayLogservice;
import com.example.service.imp.Refunlogserviceimp;
import com.example.util.SnowFlake;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;

@RestController
public class PayContrller {
    Logger logger = LoggerFactory.getLogger(getClass());//
    /*
    支付控制器
     */
    @Autowired
    private Refunlogserviceimp refunlogserviceimp;
    @Autowired
    private PayLogservice payLogservice;

    @PostMapping("/pay")

    public Map<String, String> toPAY(@RequestParam("id") Integer id) throws UnsupportedEncodingException, AlipayApiException {
        PayLog bySN = payLogservice.find(id);
        //引入支付宝dome  zhf
        String s = Alipay.generatePCPAYHTML(bySN.getSn(), bySN.getTotal_amount(), bySN.getTitle(), bySN.getInfo());
        System.out.println("--------------支付宝生成的页面  传递到前端-----------------------   ");
        System.out.println(s);
        Map M = new HashMap();
        M.put("html", s);
        return M;
    }

    /*
    支付宝异步通知接口
     */
    @PostMapping("/alipay_notify")
    @ResponseBody
    public String AlipayNotufy(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
//        检查异步通知签名是不是合法
        if (!Alipay.isValidate(request)) {
            System.out.println("验证失败");
            return "fail";
        } else {


            //验证成功
            //sn支付宝号
            String sn = request.getParameter("out_trade_no");
            //支付宝交易号
            String pay_sn = request.getParameter("trade_no");
            //付款金额
            String total_amount = request.getParameter("total_amount");
            System.out.println(total_amount);
            //支付状态
            String status = request.getParameter("trade_status");
            if (StringUtils.isEmpty(sn)) {
                logger.info("订单编号是空");
                return "fail";
            }
            if (StringUtils.isEmpty(pay_sn)) { //支付宝交易号是生成的付款页面  提交表单里面的
                logger.info("支付宝交易号是空");
                return "fail";
            }
            if (StringUtils.isEmpty(total_amount)) {
                logger.info("支付的金额是空");
                return "fail";
            }
            if (StringUtils.isEmpty(status)) {
                logger.info("订单状态是空是空");
                return "fail";
            }
            //上面都不是空  下面
            PayLog bySN = payLogservice.findBySN(sn);//根据订单的进行查询
            if (bySN == null) {
                logger.info("订单编号不存在-------------->" + sn);
                return "fail";
            }
            if (bySN.getTotal_amount() - Double.parseDouble(total_amount) > 0 || bySN.getTotal_amount() - Double.parseDouble(total_amount) < 0) {
                logger.info("支付金额不存在-------------->" + sn);
                return "fail";
            }
            //所有合法
            bySN.setPay_sn(sn);
            bySN.setPay_sn(pay_sn);
            bySN.setStatus(PayLog.pay_status_paid);//已经支付
            bySN.setTimetopay(new Date());
            int updatesave = payLogservice.updatesave(bySN);
            System.out.println(updatesave);
            return "success";
        }
    }




    /*
    支付宝订单查询

     */

    @RequestMapping("/view")
    @ResponseBody
    public String VIEW(@RequestParam("sn")String sn) throws AlipayApiException {
        PayLog bySN = payLogservice.findBySN(sn);
        //调用支付宝接口查询
        if (bySN!=null){
            String s = Alipay.viewDateil(sn);
            logger.info(s);
            return s;
        }
        /*  10000都是查询成功 订单存在
        "alipay_trade_query_response":{"code":"10000","msg":"Success","buyer_logon_id":"que***@sandbox.com","buyer_pay_amount":"0.00","buyer_user_id":"2088102181573732","buyer_user_type":"PRIVATE","invoice_amount":"0.00","out_trade_no":"YLRC887c7330da374dac967612cf3f53f40d","point_amount":"0.00","receipt_amount":"0.00","send_pay_date":"2021-01-03 19:53:18","total_amount":"20.36","trade_no":"2021010322001473730501416800","trade_status":"TRADE_SUCCESS"},"sign":"MTVjdwhoHarYCypU6yyo6L/lr/FLb3Nkj9eTB3DfzwnN4Ur+DONDm46aoFZX/0ZAU2dHQRuoc5gxIeIVA4M+3GVfJYbAU2yye1aZ3SnoW3M36iKf2aaWoFTb0O3+fHhbaUZBEVFxfEPNfdjHt47B8c193WMKZTl641r6jcFU+hlToCqYZ4K2LTlfeECQyVzvINxLn/6cU5AisSKPfpQdILa3FfH/xskFH7j1w0TX
        XEQ9yzNx6ivC6m7IPcE0HGZJPtckyfng4puFr4vIWZN68oO88jv2iJ7UoOjCdlgTvzSi+9k56+QeV2FLKlbFGC06XI7PfiF2Bf8v64viwxebVg=="}
         */
        return "查询失败 sn不存在";

    }
 /*
 关闭订单 待支付的可以关闭
  */

     @RequestMapping("/clos")
    @ResponseBody
    public String closePay(@RequestParam("sn")String sn) throws AlipayApiException {
     PayLog bySN = payLogservice.findBySN(sn);
     if (bySN!=null){
         String s = Alipay.closePay(sn);
         logger.info(s);
         JSONObject p=JSONObject.parseObject(s);
         int code=p.getJSONObject("alipay_trade_close_response").getInteger("code");
         if (code!=10000){
             String sub_msg1 = p.getJSONObject("alipay_trade_close_response").getString("sub_msg");//状态码
                return sub_msg1;
         }
         String sub_msg = p.getJSONObject("alipay_trade_close_response").getString("sub_msg");//状态码
         /*
         修改状态
          */
         PayLog payLog=new PayLog();
         payLog.setSn(sn);
         payLog.setStatus(PayLog.pay_status_closed);//修改状态
         int updatesavec = payLogservice.updatesavec(payLog);
         return sub_msg;
     }
     return "订单不存在无法关闭";
/*
 {"alipay_trade_close_response":{"code":"40004","msg":"Business Failed","sub_code":"ACQ.TRADE_NOT_EXIST","sub_msg":"交易不存在"},"sign":"Anz+htsusb3S9MHwz8pXb0RYO6JkuyKGVpb59aUaniilKP6/2DxNB10UiNlYKu77SwBy7lrjfw7nS95i+CKMBRutamKn46QXjU+/+LvEWTsuFwrJ4W2JpAOJIneq4z8w9amzTY/emXvpiP7A4GnfmvbcjPDPwTrqr8+ib+2Qj+SCf4TSSMtZQT5xJ+zC3QX33VWlItz8rBxr+zwkZifl7b3egK11swf8bB5EHazAj6Kc3jde1Y

 WACeHsTCSa2t4BYFH4IN0UY7OyBRgH0c16o6tvEJTQN+M/plI58GzgiUuPwAYRiNd2+nD5oLSwrDHyIJQzrTkrMxhvgUjMTJr38g=="}
 */
 }
 /*
 退款接口 支付部分退款
  */
    @RequestMapping("/refundcc")
    @ResponseBody
    public String REFUND(PayLog payLog) throws AlipayApiException {
        payLog.setRefundsn_sn(SnowFlake.generateSN("REFUNDSN", ""));//增加退款编号  uuid生成都是唯一的 编号记住
        PayLog payLog1 = payLogservice.find(payLog.getId());//根据id查询
        //状态要已支付       已退款 待支付 都是无法退款
        if (payLog1.getStatus() == PayLog.pay_status_waiting || payLog1.getStatus() == PayLog.pay_status_closed || payLog1.getStatus() == PayLog.Pay_status_refunded) {
            return "无法退款";
        }
        if (payLog1 == null) {
            return "不存在这个订单";
        }
        Statistics Balance = refunlogserviceimp.Statisticsrefund(payLog.getId());
        if ((Balance.getRefund() + payLog.getRefund_amount()) > payLog1.getRefund_amount()) {//传递的值是不是小于 所有的值
            //  部分退款统计加现在传递的数字 不能大于支付的余额
            return "无法退款";
        }
        if ((payLog1.getTotal_amount() - payLog.getTotal_amount()) <= 0) {//就是退款的金额是不是小于消费金额
            return "退款金额超过购买金额";
        }
        //上面都没有问题
        if (payLog.getRefundsn_sn() == null) {
            return "退款编号不存在";
        }
        String refund = Alipay.refund(payLog1.getSn(), payLog.getRefund_amount(), payLog.getRefund_info(), payLog.getRefundsn_sn());
        logger.info(refund);
        JSONObject jsonObject = JSONObject.parseObject(refund);
        Integer integer = jsonObject.getJSONObject("alipay_trade_refund_response").getInteger("code");
        System.out.println();
        if (integer != 10000) { //10000就是退款成功
            String sub_msg = jsonObject.getJSONObject("alipay_trade_refund_response").getString("sub_msg");//状态码
            return sub_msg;

        }

        PayLog payLog3 = new PayLog();
        if (payLog.getRefund_amount() - payLog1.getRefund_amount() == 0) {//全额退款
            payLog3.setStatus(PayLog.Pay_status_refunded);//修改部分退款
            payLog3.setSn(payLog1.getSn());
            int modifystatus = payLogservice.Modifystatus(payLog3);
            System.out.println(modifystatus);
            //插入  记住部分插入 只需要修改一个 状态就可以了
            Refundlog refundlog = new Refundlog();
            refundlog.setPayLogid(payLog.getId());
            refundlog.setRefund_amount(payLog.getRefund_amount());
            refundlog.setRefund_info(payLog.getRefund_info());
            refundlog.setRefundtime(new Date());
            refunlogserviceimp.Insertdataintorefundtable(refundlog);

            return "部分退款成功"; } else {
            payLog3.setStatus(PayLog.Pay_status_refunded);//修改成已退款
            payLog3.setSn(payLog1.getSn());
            payLog3.setRefund_amount(payLog.getRefund_amount());
            payLog3.setRefund_info(payLog.getRefund_info());
            int updatesava = payLogservice.updatesava(payLog3);
            //插入  全部退款成功  退款成功   修改数据
            Refundlog refundlog = new Refundlog();
            refundlog.setPayLogid(payLog.getId());
            refundlog.setRefund_amount(payLog.getRefund_amount());
            refundlog.setRefund_info(payLog.getRefund_info());
            refundlog.setRefundtime(new Date());
            refunlogserviceimp.Insertdataintorefundtable(refundlog);
            return "退款成功";
        }
        /*
        退款成功
        {"alipay_trade_refund_response":{"code":"10000","msg":"Success","buyer_logon_id":"que***@sandbox.com","buyer_user_id":"2088102181573732","fund_change":"Y","gmt_refund_pay":"2021-01-05 17:30:08","out_trade_no":"YLRCedea5a408c924531aa20051bea270d3a","refund_fee":"5.32","send_back_fee":"0.00","trade_no":"2021010522001473730501417905"},"sign":"I3bE5TcppdmoohnX0DnHmlZ/+pNuvuWF2j3DOpPuotz8kZoLL5fQ+gMgM7nhhQdoXbPtq45BJX3db3unLCItGfdBWfWtcyg6jmowyil0qtKwjD1TaISIMHEyUpGznwzTTHbWSSxpIN1/PzSqszqXkwRDdoig0JsoHVcMQyLI2Dkmbm6RI7AmSaOdMI3U6F+rkj5OvaBcFSgO5Yx8wLPXS/Bx/kyYFMLcT3SAWXDlNRWK97pXUJ8CcEX9AqfPSEiAjh4XM8BfO/eSZ4bIqURFifvICwKAcwMZJSCKRNe57BQwwURrqTN7Exep6Oh8dQ2NFH/9OPK4t9fdKGek+FZ9fQ=="}
         进行修改


    }

         */
    }
}
